package org.iweb.web.filter;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.iweb.ioc.ServiceLookup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class MainFilter implements Filter {	

	private String staticRegExp;

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;

		if (request.getRequestURI().matches(staticRegExp)) {
			arg2.doFilter(arg0, arg1);
			return;
		}

		if (request.getRequestURI().matches(".*/context-reload$")) {
			arg2.doFilter(arg0, arg1);
			return;
		}
		
		Object filter;
		Class filterClass;
		Method method;
		org.iweb.web.filter.Filter ann;

		for (String filterId : FilterFactory.getInstance().getRegister()
				.getFilters().keySet()) {
			filterClass = FilterFactory.getInstance().getRegister()
					.getFilters().get(filterId);

			filter = ServiceLookup.getInstance().get(filterId);
			ann = (org.iweb.web.filter.Filter) filterClass
					.getAnnotation(org.iweb.web.filter.Filter.class);

			try {
				method = filterClass.getMethod(ann.filterMethod(),
						HttpServletRequest.class, HttpServletResponse.class);
				method.invoke(filter, request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		staticRegExp = arg0.getInitParameter("staticRegExp");
	}
	
}
